import React, { ChangeEvent, createRef } from 'react';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
// import { uploadPhoto } from "../../api/api/upload";
import '@/assets/css/mySnow.css';
import { ImageInput } from './style';
import { uploadPhoto } from '@/services/upload';

interface RichTextEditorProps {
  text: string;
  setText: (text: string) => void;
}

const imgRef = createRef<HTMLInputElement>();

const modules = {
  toolbar: {
    container: [
      [{ header: [1, 2, 3, 4, 5, 6, false] }],
      ['bold', 'italic', 'underline', 'strike', 'link'], // 加粗、斜体、下划线、删除线、链接
      ['blockquote', 'code-block', 'image'], //引用、代码块

      [{ list: 'ordered' }, { list: 'bullet' }],
      [{ script: 'sub' }, { script: 'super' }], // 上标/下标

      [{ color: ['black'] }, { background: [] }], // 主题默认下拉，使用主题提供的值
      [{ font: [] }],
      [{ align: [] }],

      ['clean'], // 清除格式
    ],
    handlers: {
      image: () => {
        imgRef.current?.click();
      },
    },
  },
};

const RichTextEditor: React.FC<RichTextEditorProps> = ({ text, setText }) => {
  const onChange = (value: string) => {
    setText(value);
  };
  const clickImage = async (e: ChangeEvent<HTMLInputElement>) => {
    const formData = new FormData();
    formData.append('file', e.target.files ? e.target.files[0] : '');
    const res = await uploadPhoto(formData);
    if (res.data.code === 200) {
      setText(text + `<img src="${res.data?.data?.url}"/>`);
    }
  };
  return (
    <div>
      <ReactQuill
        theme="snow"
        value={text}
        onChange={onChange}
        placeholder="请输入文本..."
        modules={modules}
        className="ql-editor"
      />
      <ImageInput ref={imgRef} onChange={clickImage}></ImageInput>
    </div>
  );
};

export default RichTextEditor;
